package com.example.game_11_sleep_game12

import android.content.res.AssetFileDescriptor
import android.media.MediaPlayer
import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel

class MainActivity : FlutterActivity() {

    var next_id = 0
    var mediaPlayers = mutableMapOf<Int, MediaPlayer>()

    override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
        super.configureFlutterEngine(flutterEngine)


        MethodChannel(
            flutterEngine.dartExecutor.binaryMessenger,
            "music_channel"
        ).setMethodCallHandler { call, result ->
            when (call.method) {
                "lead" -> lead(call, result)
                "play" -> play(call, result)
                "stop" -> stop(call, result)
            }
        }

    }


    private fun lead(call: MethodCall, result: MethodChannel.Result) {
        var path = call.argument<String>("path") ?: run {
            return
        }
        var loop = call.argument<Int>("loop") ?: run {
            return
        }

        try {
            var afd: AssetFileDescriptor = assets.openFd(path)
            var player = MediaPlayer().apply {
                setDataSource(afd.fileDescriptor, afd.startOffset, afd.length)
                prepareAsync()
            }

            var id = next_id++
            if(loop == 1){
                player.isLooping = true
            }
            mediaPlayers[id] = player
            player.setOnPreparedListener {
                result.success(id)
            }

        } catch (e: Exception) {
            result.error("lead", "lead", null);
        }
    }

    private fun play(call: MethodCall, result: MethodChannel.Result){
        var id = call.argument<Int>("id") ?: run {
            return
        }
        var player = mediaPlayers[id]
        if(player == null){
            result.error("play", "play", null);
            return
        }

        try {
            player.start()
            result.success(null)
        }

        catch (e : Exception){
            result.error("play", "play", null);

        }

    }
    private fun stop(call: MethodCall, result: MethodChannel.Result){
        var id = call.argument<Int>("id") ?: run {
            return
        }
        var player = mediaPlayers[id]
        if(player == null){
            result.error("stop", "stop", null);
            return
        }

        try {
            player.stop()
            result.success(null)
        }

        catch (e : Exception){
            result.error("stop", "stop", null);

        }

    }

}
